<template>
    <div>
        <h2>{{ $t('user.manager.title') }}</h2>
        <el-form :model="searchForm" label-width="auto">
            <el-form-item :label="$t('user.manager.keyword')" size="large">
                <el-input v-model="searchForm.key" :placeholder="$t('user.manager.keyword_placeholder')" />
            </el-form-item>
            <el-form-item :label="$t('user.manager.role')" size="large">
                <el-select v-model="searchForm.role_id" :placeholder="$t('user.manager.role_placeholder')">
                    <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
            </el-form-item>
            <div class="btn-list">
                <el-button color="#435764" @click="resetFilter">{{ $t('golbal.btn_text_1') }}</el-button>
                <el-button color="#F06423" @click="getUserList">{{ $t('golbal.btn_text_2') }}</el-button>
            </div>
        </el-form>
        <p class="search-res-num">{{ $t('user.manager.search_res', { count: pagination.total }) }}</p>
        <QuickFilter @filter-change="handleFilterChange" />
        <div class="btn-list">
            <el-button color="#F06423" icon="Plus" @click="addUser">{{ $t('user.manager.add') }}</el-button>
            <el-button color="#435764" icon="Download" @click="downloadTemplate">{{ $t('user.manager.download_template') }}</el-button>
            <el-upload :show-file-list="false" accept="text/csv" :http-request="handleUpload">
                <el-button color="#F06423" icon="Upload">{{ $t('user.manager.batch_import') }}</el-button>
            </el-upload>
            <el-button color="#F06423" icon="Delete" v-if="checkedUser.length" @click="delUser(undefined)">{{ $t('user.manager.batch_delete') }}</el-button>
        </div>
        <el-table stripe :data="list" v-loading="loading" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" />
            <el-table-column sortable :label="$t('user.manager.col_name')">
                <template #default="{ row }">
                    <div class="user-box" @click="goPage(`/console/user/${row.id}?courseId=${courseId}`)">
                        <div class="user-picture pic">
                            <img :src="row.avatar_url" class="ele" v-if="row.avatar_url" />
                            <el-icon size="20" color="#fff" v-else><User /></el-icon>
                        </div>
                        <div class="user-info">{{ row.last_name }} {{ row.first_name }}</div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="email" :label="$t('user.manager.col_email')" width="200" />
            <el-table-column sortable prop="code" :label="$t('user.manager.col_code')" />
            <el-table-column :label="$t('user.manager.col_role')" width="100">
                <template #default="{ row }">
                    {{ roleStore.roles.find(item => item.id === row.role_id)?.name }}
                </template>
            </el-table-column>
            <el-table-column :label="$t('user.manager.col_action')" width="120">
                <template #default="{ row }">
                    <el-button size="small" circle icon="Edit" @click="editUser(row)"></el-button>
                    <el-button size="small" circle icon="Delete" @click="delUser(row)"></el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination-box">
            <el-pagination
                size="small"
                background
                v-model:page-size="pagination.limit"
                v-model:current-page="pagination.page"
                layout="sizes, prev, pager, next"
                :total="pagination.total"
                :page-sizes="[10, 20, 50, 100]"
                class="mt-4"
                :hide-on-single-page="true"
                @size-change="getUserList"
                @current-change="getUserList"
            />
        </div>

        <!-- 删除用户 -->
        <el-dialog v-model="delDialog" width="400" :title="$t('user.manager.delete_title')" :close-on-click-modal="!delLoading" class="mobile-dialog">
            <p>{{ $t('user.manager.delete_confirm', { name: checkedUser.length === 1 ? `${checkedUser[0].last_name} ${checkedUser[0].first_name}` : $t('user.manager.delete_multi') }) }}</p>
            <template #footer>
                <el-button color="#F06423" @click="deleteHandle" :loading="delLoading">{{ $t('golbal.btn_text_4') }}</el-button>
                <el-button @click="delDialog = false" color="#435764" :loading="delLoading">{{ $t('golbal.btn_text_3') }}</el-button>
            </template>
        </el-dialog>

        <!-- 批量注册用户 -->
        <el-dialog v-model="importUserDialog" width="1000" :title="$t('user.manager.import_title')" class="mobile-dialog">
            <el-table stripe :data="importUser" style="width: 100%" max-height="78vh">
                <el-table-column prop="account" :label="$t('user.manager.col_account')" width="160" />
                <el-table-column :label="$t('user.manager.col_name')" width="140">
                    <template #default="{ row }">{{ row.first_name }}{{ row.last_name }}</template>
                </el-table-column>
                <el-table-column prop="email" :label="$t('user.manager.col_email')" />
                <el-table-column prop="role_name" :label="$t('user.manager.col_role')" width="100" />
                <el-table-column fixed="right" :label="$t('user.manager.col_status')" width="80">
                    <template #default="{ row }">
                        <el-icon size="16" color="#67C23A" v-if="row.status === 'success'"><CircleCheck /></el-icon>
                        <el-icon size="16" color="#E6A23C" v-if="row.status === 'skipped'"><Warning /></el-icon>
                        <el-icon size="16" color="#F56C6C" v-if="row.status === 'failed'"><CircleClose /></el-icon>
                    </template>
                </el-table-column>
                <el-table-column prop="message" :label="$t('user.manager.col_message')" width="200" />
            </el-table>
            <template #footer>
                <el-button color="#F06423" @click="importUserDialog = false">{{ $t('golbal.btn_text_5') }}</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import type { FormInstance, UploadRequestOptions } from 'element-plus'

import QuickFilter from '@/components/QuickFilter.vue'

import { goPage, createDownloadA } from '@/utils/global'

import UserService from '@/api/user'
import type { ImportResultItem, UserInfo } from '@/types/user'

import { useRoleStore } from '@/stores/role'

import CourseService from '@/api/course'
import type { CourseItem, ImportMemberItem } from '@/types/course'
import type { Pagination } from '@/types/global'

interface FilterParams {
    lastName: string
    firstName: string
}

const route = useRoute()
const roleStore = useRoleStore()
const courseId = computed(() => Number(route.params.courseId))
const loading = ref(false)
const downloadTemplate = () => {
    const csvUrl = new URL('@/assets/template/importUsers.csv', import.meta.url).href
    createDownloadA(csvUrl, 'importUsers.csv')
}

const searchForm = reactive({
    key: '',
    role_id: '',
})
const roleList = computed(() => roleStore.roles)
const resetFilter = () => {
    searchForm.key = ''
    searchForm.role_id = ''
    getUserList()
}

// 姓氏和名字 筛选
const filters = ref<FilterParams>({
    lastName: 'all',
    firstName: 'all',
})
const handleFilterChange = (newFilters: FilterParams) => {
    filters.value = newFilters
    getUserList()
}

// 用户列表
const list = ref<UserInfo[]>([])
const checkedUser = ref<UserInfo[]>([])
const handleSelectionChange = (val: UserInfo[]) => {
    checkedUser.value = val
}
const addUser = () => {
    goPage('/console/user/create')
}
const editUser = (user: UserInfo) => {
    goPage(`/console/user/edit?userId=${user.id}`)
}
const delUser = (user?: UserInfo) => {
    if (user) checkedUser.value = [user]
    delDialog.value = true
}
function getUserList() {
    loading.value = true
    const searchData = {
        key: searchForm.key,
        role_id: searchForm.role_id,
        first_initial: filters.value.firstName,
        last_initial: filters.value.lastName,
        page: pagination.value.page,
        limit: pagination.value.limit,
    }
    UserService.listWithPagination(searchData)
        .then(res => {
            list.value = res.items
            pagination.value = res.pagination || pagination.value
        })
        .finally(() => {
            loading.value = false
        })
}

// 删除用户
const delDialog = ref(false)
const delLoading = ref(false)
const deleteHandle = () => {
    delLoading.value = true
    UserService.delete(checkedUser.value.map(item => item.id))
        .then(() => {
            delDialog.value = false
            getUserList()
        })
        .finally(() => {
            delLoading.value = false
        })
}

// 批量注册用户
const importUser = ref<ImportResultItem[]>([])
const importUserDialog = ref(false)
const handleUpload = (options: UploadRequestOptions) => {
    loading.value = true
    const { file } = options
    const data = new FormData()
    data.append('file', file)
    data.append('filename', file.name)
    UserService.import(data)
        .then(res => {
            importUser.value = res.data
            importUserDialog.value = true
        })
        .finally(() => {
            loading.value = false
        })
}

// 分页器
const pagination = ref<Pagination>({
    page: 1,
    limit: 10,
    total: 10,
})

watch(
    () => route.fullPath,
    () => {
        getUserList()
    },
)

onMounted(() => {
    getUserList()
})
</script>

<style lang="less" scoped>
h2 {
    margin-bottom: 30px;
    font-size: 30px;
    font-weight: normal;
    line-height: 1.2;
    color: #000;
}

.el-form {
    border: 1px solid #dee2e6;
    border-radius: 4px;
    padding: 15px;
    background-color: #f8f9fa;

    display: flex;
    flex-wrap: wrap;
    gap: 0 30px;

    .el-form-item {
        width: calc(50% - 15px);
    }

    .btn-list {
        margin-top: 0;
    }
}

.search-res-num {
    margin-top: 8px;
    margin-bottom: 15px;
    color: #4c4c4c;
    font-size: 15px;
}

.user-box {
    cursor: pointer;

    .user-info {
        flex-direction: column;
        justify-content: flex-start;
        align-items: flex-start;
        gap: 4px;
    }
}

.btn-list {
    margin-bottom: 15px;
    display: flex;
    justify-content: flex-end;
    gap: 15px;
    width: 100%;

    .el-button + .el-button {
        margin-left: 0;
    }
}

:deep(.el-dialog) {
    .add-member-form {
        border: none;
        border-radius: 0;
        padding: 0;
        background-color: transparent;

        .el-form-item {
            width: 100%;
        }
    }
}

.user-select-opt {
    margin: 10px 0;
    height: auto;
    line-height: 1;
}
</style>
